<template>
  <el-button @click="handleClick" type="primary">
    <slot></slot>
  </el-button>

  <div class="m--choose-icon-dialog-body-height">
    <el-dialog :title="title" v-model="dialogVisible">
      <div class="container">
        <div
          class="item"
          v-for="(item, index) in Object.keys(ElIcons)"
          :key="index"
          @click="clickItem(item)"
        >
          <div class="text">
            <component :is="`el-icon-${toLine(item)}`"></component>
          </div>
          <div class="icon">{{ item }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue'
  import * as ElIcons from '@element-plus/icons'
  import { toLine } from '../../../utils'
  import { useCopy } from '../../../hooks/useCopy'

  let props = defineProps<{
    // 弹出框的标题
    title: string
    // 控制弹出框的显示与隐藏
    visible: boolean
  }>()
  const emits = defineEmits(['update:visible'])

  // 拷贝一份父组件传递过来的 visible
  let dialogVisible = ref<boolean>(props.visible)

  let handleClick = () => {
    // 修改父组件的数据
    emits('update:visible', !props.visible)
  }

  let clickItem = (item: string) => {
    let text = `<el-icon-${toLine(item)} />`
    useCopy(text)
    // 复制成功后，关闭弹窗
    dialogVisible.value = false
  }

  // 监听 visible 的值
  watch(
    () => props.visible,
    (val) => {
      dialogVisible.value = val
    }
  )

  watch(
    () => dialogVisible.value,
    (val) => {
      emits('update:visible', val)
    }
  )
</script>
<style lang="scss" scoped>
  .container {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
  .item {
    width: 25%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
  }
  .text {
    font-size: 14px;
  }
  .icon {
    flex: 1;
  }
  svg {
    width: 2em;
    height: 2em;
    cursor: pointer;
  }
</style>
